#include "network.h"


char *substring(char *dst,char *src,int start,int len)
{  
	char *p=dst;  
	char *q=src;  
	int length=strlen(src); 
	if(start>=length||start<0) 
		return NULL;  
	if(len>length) 
		len=length-start; 
	q+=start;
	while(len--)  
	{   
		*(p++)=*(q++); 
	}  
	*(p++)='\0';  
	return dst;
}

//./udp 昵称
int main(int argc, const char *argv[])
{
	CLEAR();
	move_pp = 18;			//总大小24

	move_status = 1;			//总大小24
	
	int udp_fd;
	int retval;
	int input_cmd;
	ssize_t send_size;
	char broadcase_addr[16];
	struct sockaddr_in native_addr, dest_addr, recv_addr;
	socklen_t skt_len = sizeof(struct sockaddr_in);
	struct glob_info ginfo;
	struct friend_list *pos;
	pthread_t tid;
	
	strcpy(ginfo.name, argv[1]);
	ginfo.list_head = request_friend_info_node(NULL);


	ginfo.skt_fd = socket(AF_INET, SOCK_DGRAM, 0);
	if(ginfo.skt_fd == -1)
	{
		perror("申请套接字失败");
		goto request_socket_err;
	}
	
	int sw = 1;
	
	//端口绑定复用
	retval = setsockopt(ginfo.skt_fd, SOL_SOCKET, SO_REUSEADDR, &sw, sizeof(sw));
	
	retval = setsockopt(ginfo.skt_fd, SOL_SOCKET, SO_BROADCAST, &sw, sizeof(sw));
	if(retval == -1)
	{
		perror("设置程序允许广播出错");
		goto setsock_broadcase_err;
	}

	native_addr.sin_family = AF_INET;
	native_addr.sin_port = htons( all_port );
	native_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	retval = bind(ginfo.skt_fd, (struct sockaddr *)&native_addr, sizeof(native_addr));
	if(retval == -1)
	{
		perror("绑定异常");
		return -1;
	}

	pthread_create(&tid, NULL, recv_broadcast_msg, &ginfo);

	struct recv_info msg_info;

	strcpy(msg_info.name, argv[1]);//将我们的名字赋值进去
	msg_info.msg_flag = online_flag;//上线标志
	

	broadcast_msg_data(ginfo.skt_fd, &msg_info, msg_info.msg_buffer-msg_info.name);//通知别人我们上线了
	while(1)
	{	
		//M_ret();
		//MOVEDOWN(10);
		//MOVEUP(10);
		//MOVEDOWN(5);
		goto_scanf();
		//printf("显示好友链表输入：  1\n指定好友聊天请输入：3\n退出请输入：        4\n");
		
		scanf("%d", &input_cmd);

		switch(input_cmd){
			case 1:
				//打印好友链表，并且可以找寻一个好友聊天
				show_all_friend(&ginfo);
				break;
			case 2:
				//仅仅只是打印好友链表
				break;

			case 3:
				//指定好友聊天
				chat_with_friend(&ginfo, &msg_info);
				break;
			case 4:
				//下线，通知其他人我们走了
				msg_info.msg_flag = offline_flag;//下线标志
				broadcast_msg_data(ginfo.skt_fd, &msg_info, msg_info.msg_buffer-msg_info.name);//通知别人我们上线了
				break;
			default:
				 show_systems_msg();
				 printf("输入出错!\n");
				 goto_scanf();
				 break;
				
		}
		
		if(msg_info.msg_flag == offline_flag)
		{
			pthread_cancel(tid);
			pthread_join(tid, NULL);
			break;
		}	
	}
	
	close(ginfo.skt_fd);

	return 0;

setsock_broadcase_err:
bind_socket_err:
	close(udp_fd);
request_socket_err:
	return -1;

}

